package service

import (
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"shrimp-blog-server/app/dao"
	"shrimp-blog-server/app/model"
)

func (*ResourceService) AddResource(req *ghttp.Request, resources ...model.Resource) {
	if len(resources) == 0 {
		responses.ErrorResponseExit(req, "资源信息不能为空")
	}
	result, err := dao.Resource.Insert(resources...)
	if err != nil {
		g.Log("添加资源失败").Error(err)
		panic(gerror.Wrap(err, "添加资源失败"))
	}
	if result == 0 {
		responses.ErrorResponseExit(req, "添加资源失败")
	}
	responses.SuccessResponse(req)
}

func (*ResourceService) UpdateResource(req *ghttp.Request, resources ...model.Resource) {
	if len(resources) == 0 {
		responses.ErrorResponseExit(req, "资源信息不能为空")
	}
	result, err := dao.Resource.Update(resources...)
	if err != nil {
		g.Log("更新资源失败").Error(err)
		panic(gerror.Wrap(err, "更新资源失败"))
	}
	if result == 0 {
		responses.ErrorResponseExit(req, "更新资源失败")
	}
	responses.SuccessResponse(req)
}

func (*ResourceService) DeleteResource(req *ghttp.Request, id ...uint) {
	if len(id) == 0 {
		responses.ErrorResponseExit(req, "资源信息不能为空")
	}
	models := make([]model.Resource, len(id))
	result, err := dao.Resource.Delete(models...)
	if err != nil {
		g.Log("删除资源失败").Error(err)
		panic(gerror.Wrap(err, "删除资源失败"))
	}
	if result == 0 {
		responses.ErrorResponseExit(req, "删除资源失败")
	}
	responses.SuccessResponse(req)
}

func (*ResourceService) GetResource(req *ghttp.Request, id ...uint) {
	var resources []model.Resource
	var err error
	if len(id) > 0 {
		resources, err = dao.Resource.GetModelById(id...)
	} else {
		err = dao.Resource.DB().Model(dao.Resource.Table).OrderDesc(dao.Resource.Columns.Id).Scan(&resources)
	}

	if err != nil {
		g.Log("获取资源失败").Error(err)
		panic(gerror.Wrap(err, "获取资源失败"))
	}

	responses.Json(req, successCode, successMessage, resources)
}
